<template>
  <view class="almost-lottery" >
    <!-- head -->
    <view class="almost-lottery__wheel">
		<view class="almost-lottery__count">
		  <text>每次抽奖消耗 <span class="text-lottery">{{ consume }}</span> 次抽奖次数</text>
		</view>
		<view class="almost-lottery__count">
		  <text>我的抽奖次数： <span class="text-lottery">{{ this.point }}</span> </text>
		</view>	
<!-- 				<view class="center-btn" @click="handleDrawStart()">
				  <image class="btn-image" src="/static/almost-lottery/lottery-start.png"></image>
				</view> -->
    </view>
    <!-- action -->
    <view class="almost-lottery__action-dev" @tap="handleInitCanvas" v-if="isDev">
      <text class="text">重新生成画板-开发模式使用</text>
    </view>
    <!-- lottery -->
    <view class="almost-lottery__wheel">
      <almost-lottery
        :lottery-size="lotteryConfig.lotterySize"
        :action-size="lotteryConfig.actionSize"
        :ring-count="20"
        :duration="5"
        :self-rotaty="false"
        :img-circled="true"
        :canvasCached="true"
        :prize-list="prizeList"
        :prize-index="prizeIndex"
        @reset-index="prizeIndex = -1"
        @draw-before="handleDrawBefore"
        @draw-start="handleDrawStart"
        @draw-end="handleDrawEnd"
        @finish="handleDrawFinish"
        v-if="prizeList.length"
      />

    </view>
    <!-- rule -->
    <view class="almost-lottery__rule">
      <view class="rule-head">抽奖规则</view>
      <view class="rule-body">
        <view class="item">
          <view class="title">抽奖获取：</view>
          <view class="text">
            <text>参与高等级签约或者精选活动签约，不定时会有抽奖次数赠送。</text>
          </view>
        </view>
        <view class="item">
          <view class="title">领奖方式：</view>
          <view class="text">
            <text>积分奖和现金红包奖我们采取系统自动发放至用户账户。实物奖品中奖者，请在七天内由用户自己咨询在线客服领取，我们将以快递寄送到中奖者提供的有效收获地址。（超过领取时间我们将视为自动放弃）</text>
          </view>
        </view>
<!--          <view class="item">
			  <view class="title">积分计算：</view>
			  <view class="text">积分将根据参与者在活动期间完成的指定任务进行累积。不同任务的积分奖励将在活动开始前明确公布。</view>
			</view> -->
          <view class="item"><view class="title">抽奖变更：</view><view class="text">平台会不定期对抽奖奖品进行变更。</view></view>
          <view class="item"><view class="title">法律责任：</view><view class="text">平台用户参与者需遵守活动规则及相关法律法规，如有违反，平台有权取消其参与资格并追究相应法律责任。</view></view>
          <view class="item"><view class="text">参与者请务必在活动开始前详细阅读并理解以上规则，以确保能够顺利参与抽奖。祝大家好运！</view></view>
      </view>
    </view>
	<view v-show="isShowBox" class="profit_box">
		<view class="profit_bar">
			<view class="profit_tit">中奖记录</view><view class="close" @click="choseBox">✕</view>
		</view>
		<view class="profit_contain" @scroll="handleScroll">
			<view class="det_item" v-for="(item, index) in list" :key="index">
				<view class="det_tit">{{item.reason}}</view>
				<view class="det_time">{{item.create_time}}</view>
				<view class="det_money"><span>{{item.money}}</span>元</view>
			</view>
		</view>
		<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
	</view>
	<view class="cover" v-show="isShowBox"></view>
  </view>
</template>

<script>
import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
import { clearCacheFile, clearStore } from '@/uni_modules/almost-lottery/utils/almost-utils.js'
import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
  export default {
    name: 'Home',
    components: {
      AlmostLottery,
	    uniPopupDialog
    },
	  data () {
      return {
        // 开启调试模式
        isDev: false,
        // 以下是转盘配置相关数据
        lotteryConfig: {
          // 抽奖转盘的整体尺寸，单位rpx
          lotterySize: 700,
          // 抽奖按钮的尺寸，单位rpx
          actionSize: 200
        },
        // 以下是奖品配置数据
        // 奖品数据
        prizeList: [],
				// 奖品是否设有库存
				onStock: false,
        // 中奖下标
        prizeIndex: -1,
        // 是否正在抽奖中，避免重复触发
        prizeing: false,
        // 以下为中奖概率有关数据
        // 是否由前端控制概率，默认不开启，强烈建议由后端控制
        onFrontend: false,
        // 权重随机数的最大值
        prizeWeightMax: 0,
        // 权重数组
        prizeWeightArr: [],
        
        // 以下为业务需求有关示例数据
        // 积分余额
        myjifen: 0,
        // 每次消耗的积分
        consume: 0,
		isShowBox: false,
		inviteList: [],
		list: [],
		pageIndex: 1,
		pageSize: 10,
		totalPages: 0,
		page: 0,
		lastPage: 0,
		loadMoreText: "加载中...",
		showLoadMore: false,
		current: 1,
		current_page:0
      }
    },
    computed: {
      isApple () {
        return uni.getSystemInfoSync().platform === 'ios'
      }
    },
		onNavigationBarButtonTap(val) {
				this.isShowBox = true
				this.page = 0;
				this.current_page=0;
				this.list=[];
				this.$nextTick(() => {
					const el = document.querySelector('.profit_contain');
					el.scrollTo(0,0)
				});
				this.checkInvite(0);

		},
		onHide() {
			this.ifOnShow = true
		},
		onShow() {
			if (this.ifOnShow) {
				// this.getData();
			}
			let pages = getCurrentPages();
			let currPage = pages[pages.length-1];
			if (currPage.$vm.bank_id){
				this.bank_id = currPage.$vm.bank_id;
				// this.loadData();
			}
		},			
    methods: {
      // 重新生成
      handleInitCanvas () {
		clearCacheFile()
        clearStore()
        this.prizeList = []
        this.getPrizeList()
      },
	  checkInvite(current){
	  	var info = uni.getStorageSync("userinfo");
	  	if (info.token) {
	  		let page = this.page;
	  		if(current > 0){
	  			let page = current;
	  		}
	  		let timestamp = this.helper.now();
	  		let sign = this.helper.setSign(['page='+page, 'token=' + info.token, 'timestamp=' +
	  			timestamp
	  		]);
	  		this.helper.req({
	  			api: "getDrawRecords",
	  			timestamp: timestamp,
	  			data: {
	  				token: info.token,
	  				page:page,
	  			},
	  			header: {
	  				sign: sign
	  			},
	  			method: 'GET',
	  		}).then(res => {
				//console.log(res)
	  		let current_page = res.data.data.list.current_page;
	  		let last_page = res.data.data.list.last_page;
	  		this.page = current_page + 1;
	  		this.lastPage = last_page;
	  		this.list = this.list.concat(res.data.data.list.data);
	  		if (this.page >= this.lastPage) {
	  			this.loadMoreText = "没有更多数据了!"
	  		}						
	  			uni.stopPullDownRefresh();
	  			uni.hideLoading();
	  		})
	  	} else {
	  		uni.hideLoading();
	  	}
	  },
	  choseBox(){
	  	this.isShowBox = false
	  	this.current = 1
	  },
      // 获取奖品列表
      async getPrizeList () {
        uni.showLoading({
          title: '奖品准备中...'
        })
				
        // 等待接口返回的数据进一步处理
        let res = await this.requestApiGetPrizeList()

      },
			// 获取奖品列表 接口
			requestApiGetPrizeList () {
				uni.showLoading({
					title: '奖品准备中...'
				})
				// 请求奖品列表
				var info = uni.getStorageSync("userinfo");
				let timestamp = this.helper.now();
				let sign = this.helper.setSign(['token='+info.token,'timestamp='+timestamp]);
				this.helper.req({
					api:"getLottery",
					timestamp:timestamp,
					data:{token:info.token},
					header:{sign:sign},
					method:'GET',
				}).then(res=>{
					this.point	= res.data.data.point;
					this.consume	= res.data.data.consume;
					this.prizeList = res.data.data.list;
					// 遍历奖品列表，为每个奖品添加 prizeImage 属性
					this.prizeList.forEach(prize => {
						prize.prizeImage = require('@/static/lottery-prize/' + prize.imageFileName);
						prize.prizeName	= prize.name
					});
					setTimeout(() => {
						uni.hideLoading();
					}, 300);
				})
			},
      // 抽奖开始之前
      handleDrawBefore (callback) {
        console.log('抽奖开始之前')
        let flag = true
          flag = true

        
        callback(flag)
      },
      // 本次抽奖开始
      handleDrawStart () {
        console.log('触发抽奖按钮')
        if (this.prizeing) return
        this.prizeing = true
        
        this.tryLotteryDraw()
      },
      // 尝试发起抽奖
      tryLotteryDraw () {
        console.log('旋转开始，获取中奖下标......')
          this.remoteGetPrizeIndex()
      },
      // 本地获取中奖下标
      localGetPrizeIndex () {
        console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
        // 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
        // 后端控制概率的情况下，通常会直接返回 prizeId
        if (!this.prizeWeightMax || !this.prizeWeightArr.length) {
        	console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 prizeWeight 参数似乎配置不正确###')
        	return
        }
        console.log('当前权重最大值为 =>', this.prizeWeightMax)
        
        // 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
        let randomWeight = Math.ceil(Math.random() * this.prizeWeightMax)
        console.log('本次权重随机数 =>', randomWeight)
        
        // 生成大于等于随机权重的数组
        let tempMaxArrs = []
        this.prizeList.forEach((item) => {
          if (item.prizeWeight >= randomWeight) {
            tempMaxArrs.push(item.prizeWeight)
          }
        })
        console.log('tempMaxArrs', tempMaxArrs)
        
        // 如果大于随机权重的数组有值，先对这个数组排序然后取值
        // 反之新建一个临时的包含所有权重的已排序数组，然后取值
        let tempMaxArrsLen = tempMaxArrs.length
        if (tempMaxArrsLen) {
          tempMaxArrs.sort((a, b) => a - b)
          // 取值时，如果存在多个值，分两种情况
          if (tempMaxArrsLen > 1) {
            // 检查是否存在重复的值
            let sameCount = 0
            for (let i = 0; i < tempMaxArrs.length; i++) {
              if (tempMaxArrs[i] === tempMaxArrs[0]) {
                sameCount++
              }
            }
            
            // 值不相等的情况下取最接近的值，也就是第1个值
            if (sameCount === 1) {
              this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
            } else {
              // 存在值相等时，随机取值，当然这里你可以自己决定是否随机取值
              let sameWeight = tempMaxArrs[0]
              let sameWeightArr = []
              let sameWeightItem = {}
              this.prizeWeightArr.forEach((item, index) => {
                if (item === sameWeight) {
                  sameWeightArr.push({
                    prizeWeight: item,
                    index
                  })
                }
              })
              console.log('sameWeightArr', sameWeightArr)
              sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)]
              console.log('sameWeightItem', sameWeightItem)
              this.prizeIndex = sameWeightItem.index
            }
          } else {
            this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
          }
        }
        
        console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeName)
        
        // 如果奖品设有库存
        if (this.onStock) {
          console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].prizeStock)
        }
      },
      // 远程请求接口获取中奖下标
      remoteGetPrizeIndex () {
        console.warn('###当前正在请求接口，并返回了中奖信息###')
        // 模拟请求接口获取中奖信息
        let stoTimer = setTimeout(() => {
          stoTimer = null
          
          let list = [...this.prizeList]
          
				var info = uni.getStorageSync("userinfo");
				let timestamp = this.helper.now();
				let sign = this.helper.setSign(['token='+info.token,'timestamp='+timestamp]);
				this.helper.req({
					api:"doLottery",
					timestamp:timestamp,
					data:{token:info.token},
					header:{sign:sign},
					method:'POST',
				}).then(res=>{
					if (res.data.errorcode  == 10000) {
						uni.showModal({
							title: "提示",
							content: res.data.message,
							showCancel: false,
							confirmText: "确定",
							success:function(res){
								uni.redirectTo({
									url: '/pages/games/lottery'
								});
							}
						})
						return;
					}else{
						let prizeId = res.data.data.position;
						let prizeImage =this.weburl+res.data.data.prizeImage
						list.forEach((item, index) => {
							if (item.prizeId === prizeId) {
								// 中奖下标
								this.prizeIndex = index
							}
						})
						this.targetName = res.data.message;
						// console.log('当前域名',prizeImage)
						//  console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeImage)
					}
				})
        }, 200)
      },
      // 本次抽奖结束
      handleDrawEnd () {
				// 旋转结束后，可以执行拿到结果后的逻辑
				let _this = this;
				let prizeName = this.prizeList[this.prizeIndex].name;
				this.prizeing = false
				uni.showModal({
					title: "提示",
					content: this.targetName,
					showCancel: false,
					confirmText: "确定",
					success:function(res){
					_this.getPrizeList();
					}
				})
				// this.targetName = prizeName === '谢谢参与' ? prizeName : `恭喜您，获得 ${prizeName}` 
			},
			
			handleDrawFinish(){},
			handleScroll(event) {
				this.$nextTick(() => {
					const el = document.querySelector('.profit_contain');
					const offsetHeight = el.offsetHeight;
					el.onscroll = () => {
						const scrollTop = el.scrollTop;
						const scrollHeight = el.scrollHeight;
						if ((offsetHeight + scrollTop) - scrollHeight >= -1) {
							// 触达底部
							let current = this.current;
							current++;
							this.checkInvite(current)
							console.log('current:',current)
							this.current = current
						}
					};
				});
			}	
    },
    onLoad () {
      this.prizeList = []
      this.getPrizeList()
    },
    onUnload () {
      uni.hideLoading()
    }
  }
</script>

<style lang="scss">
	page{
		background-color: #ddeafd;
		color: #56595d;
	}
  .almost-lottery {
    flex: 1;
    // background-color: #FF893F;
  }
  .center-btn {
    text-align: center;
    //margin-top: 20px; /* 调整按钮与 "我的积分" 列之间的间距 */
  }
  .btn-image {
    width: 120px; /* 设置按钮宽度 */
    height: 65px; /* 设置按钮高度 */
    /* 其他样式设置 */
  }
  .almost-lottery__head {
    position: relative;
    width: 100%;
    height: 200px;
	
    //background: url('~static/images/lottery/top-bg.png') no-repeat center center/cover;
    .action {
      position: relative;
      top: 400rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 480rpx;
      height: 88rpx;
      line-height: 88rpx;
      margin: 0 auto;
      color: #000;
      font-size: 32rpx;
      background-color: rgba(255, 136, 61, 1);
      border-radius: 44rpx;
    }
    .action-shadow {
      box-shadow: 0px 14rpx 0px 0px rgba(235, 112, 36, 1);
    }

    .tip {
      position: relative;
      top: 428rpx;
      color: #FFFFFF;
      font-size: 24rpx;
      text-align: center;
    }
  }
  
  .almost-lottery__wheel {
    text-align: center;
    .almost-lottery__count {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      padding: 20rpx 0;
    }
    .text {
      color: #56595d;
      font-size: 24rpx;
    }
  }
  
  .almost-lottery__rule {
    padding: 0 28rpx;
    color: #FFF8CB;
    .rule-head {
	    background: linear-gradient(180deg, #a0c4ff 0%, #4f8ffe 100%);
	    margin: 40rpx 10vw;
	    color: #fff;
	    text-align: center;
	    line-height: 50px;
	    font-size: 16px;
	    border-radius: 30px;
    }
    .rule-body {
      font-size: 24rpx;
      padding: 10rpx 0 40rpx;
      .item {
        display: flex;
        margin-bottom: 10rpx;
      }
      .title {
				color: #4f8ffd;
				margin-right: 5px;
      }
      .text {
        flex: 1;
	      color: #56595d;
      }
      .item-rule .text {
        display: flex;
        flex-direction: column;
      }
    }
  }
  
  .almost-lottery__action-dev {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    width: 400rpx;
    height: 80rpx;
    border-radius: 10rpx;
    text-align: center;
    background-color: red;
    margin: 0 auto 40rpx;
    .text {
      font-size: 28rpx;
    }
  }
  
  .almost-lottery__popup-wrap {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .almost-lottery {
      background: transparent;
    }
  }
  .text-lottery{
      font-size: 3.73vw;
      color: #4188ff;
      margin: 0px .53vw;
  }
	.profit_box{
		position: fixed;
		left: 5vw;
		right: 5vw;
		bottom: 0;
		top: 15vh;
		background: #fff;
		border-radius: 25rpx 25rpx 0 0;
		z-index: 2;
		display: flex;
		flex-direction: column;
		box-shadow: 0 0 15rpx #ccc;
		.profit_bar{
			height: 12vw;
			color: #5792fd;
			border-bottom: 0.5px solid #999a99;
			width: 80vw;
			margin: auto;
			.profit_tit{
				line-height: 12vw;
				font-size: 18px;
				font-weight: bold;
				text-align: center;
			}
			.close{
				width: 10vw;
				height: 12vw;
				line-height: 12vw;
				font-size: 18px;
				font-weight: bold;
				text-align: center;
				position: absolute;
				top: 0;
				right: 5vw;
				color: #999a99;
			}
		}
		.profit_contain{
			flex: 1;
			overflow-y: scroll;
			.det_item{
				padding: 3vw 3vw 0;
				position: relative;
				.det_tit{
					font-size: 18px;
					line-height: 30px;
					color: #5792fd;
				}
				.det_time{
					font-size: 12px;
					line-height: 24px;
					color:#b5b5b5;
				}
				.det_money{
					width: 24vw;
					line-height: 10vw;
					text-align: center;
					font-size: 12px;
					position: absolute;
					right: 0;
					top: 8px;
					span{
						font-size: 12px;
						color: #5792fd;
						font-weight: bold;
					}
				}
			}
		}
	}  
</style>
